package com.ziyun.erp.web.modules.production.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.ziyun.erp.common.e.order.OrderItemStatusEnum;
import com.ziyun.erp.common.e.production.OrderProductionStatusEnum;
import com.ziyun.erp.common.utils.FileUtil;
import com.ziyun.erp.common.utils.JsonUtils;
import com.ziyun.erp.common.utils.UserUtils;
import com.ziyun.erp.modules.freightages.service.SdbEctoolsRegionsService;
import com.ziyun.erp.modules.logistics.service.LogisticsTypeService;
import com.ziyun.erp.modules.order.entity.ErpOrderEntity;
import com.ziyun.erp.modules.order.service.ErpOrderService;
import com.ziyun.erp.modules.production.dto.FinancePaymentDto;
import com.ziyun.erp.modules.production.dto.ProductionCostDto;
import com.ziyun.erp.modules.production.entity.ErpOrderItemEntity;
import com.ziyun.erp.modules.production.entity.ErpOrderProductionEntity;
import com.ziyun.erp.modules.production.operate.ErpOrderStateContext;
import com.ziyun.erp.modules.production.service.ErpOrderItemService;
import com.ziyun.erp.modules.production.service.ErpOrderProductionService;
import com.ziyun.erp.modules.production.vo.ErpOrderProductionListVo;
import io.renren.common.utils.R;
import io.renren.common.validator.ValidatorUtils;
import net.sf.json.JSONArray;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;


/**
 * erp订单生产表
 *
 * @author guizhao
 * @email ...
 * @date 2018-08-22 10:32:12
 */
@RestController
@RequestMapping("production/erporderproduction")
public class ErpOrderProductionController {

    @Autowired
    private ErpOrderProductionService erpOrderProductionService;
    @Autowired
    private ErpOrderItemService erpOrderItemService;
    @Autowired
    private ErpOrderService erpOrderService;
    @Autowired
    private SdbEctoolsRegionsService sdbEctoolsRegionsService;
    @Autowired
    private LogisticsTypeService logisticsTypeService;

    /**
     * 阳逻发货
     */
    @RequestMapping("/yangluoSend")
    @RequiresPermissions("production:erporderproduction:list")
    public R yangluoSend(@RequestParam("eoItemId") Integer eoItemId, @RequestParam("csId") Integer csId, @RequestParam("pmcId") Integer pmcId) {
        return erpOrderProductionService.yangluoSend(eoItemId, csId, pmcId);
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("production:erporderproduction:update")
    public R update(@RequestBody ErpOrderProductionEntity erpOrderProduction) {
        ValidatorUtils.validateEntity(erpOrderProduction);
        erpOrderProductionService.updateAllColumnById(erpOrderProduction);//全部更新

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("production:erporderproduction:delete")
    public R delete(@RequestBody Integer[] productionIds) {
        erpOrderProductionService.deleteBatchIds(Arrays.asList(productionIds));

        return R.ok();
    }

    /**
     * 物流发货信息
     */
    @RequestMapping("/sendLogisticsInfo/{productionIds}")
    public R sendLogisticsInfo(@PathVariable("productionIds") String productionIds) {
        R re = R.ok();

        List<String> ids = Arrays.asList(productionIds.split(","));
        List<ErpOrderProductionEntity> productionEntityList = erpOrderProductionService.selectBatchIds(ids);
        long count = productionEntityList.stream().filter(item -> item.getProductionStatus().intValue() != OrderProductionStatusEnum.FINISH.toInt()).count();
        if (count > 0) {
            return R.error("生产单未生产完成");
        }

        for (ErpOrderProductionEntity erpOrderProductionEntity : productionEntityList){
            // 检查线上分配订单是否已验货确定
            if (erpOrderProductionEntity.getOnlineCash() == 1){
                String productionOrder = erpOrderProductionEntity.getProductionOrder();
                ErpOrderEntity erpOrderEntity = erpOrderService.selectById(productionOrder);
                if (erpOrderEntity.getReceivedStatus() != 1){
                    return R.error("生产单未验货确定");
                }
            }
        }

        List<ErpOrderEntity> erpOrderEntityList = erpOrderService.queryListByProductionId(ids);
        if (erpOrderEntityList == null || erpOrderEntityList.size() != 1) {
            return R.error("请勾选相同订单号添加物流");
        }

        ErpOrderEntity erpOrder = erpOrderEntityList.get(0);
        re.put("erpOrder", erpOrder);
        // 商品列表
        List<Integer> statusList = new ArrayList<>();
        statusList.add(OrderItemStatusEnum.PRODUCTION_FINISH.toInt());
        statusList.add(OrderItemStatusEnum.DELIVERED.toInt());
        List<ErpOrderItemEntity> erpOrderItemEntityList = erpOrderItemService.selectList(
                new EntityWrapper<ErpOrderItemEntity>()
                        .eq("order_no", erpOrder.getOrderNo())
                        .in("status", statusList)
                        .eq("item_del", 0)
        );
        re.put("erpOrderItemEntityList", erpOrderItemEntityList);

        // 查询省市区级联数据
        List<String> area = sdbEctoolsRegionsService.queryRegionsSascade();
        re.put("area", JSONArray.fromObject(area).toString());
        // 物流类型
        List<Map<Integer, String>> logisticsTypeList = logisticsTypeService.queryTypeList();
        re.put("logisticsTypeList", logisticsTypeList);

        return re;
    }

    /**
     * 物流发货信息(阳逻)
     */
    @RequestMapping("/sendYangluoLogisticsInfo/{productionIds}")
    public R sendYangluoLogisticsInfo(@PathVariable("productionIds") String productionIds) {
        return erpOrderProductionService.sendYangluoLogisticsInfo(productionIds);
    }

    /**
     * 生产列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("production:erporderproduction:list")
    public R list(@RequestParam Map<String, Object> params) {
//        params.put("sellerId", ErpOrderStateContext.ZIYUN_SELLER_ID);
        return erpOrderProductionService.queryPageProductionList(params);
    }

    /**
     * 阳逻生产列表
     */
    @RequestMapping("/yangluolist")
    public R yangluolist(@RequestParam Map<String, Object> params) {
        params.put("producer", ErpOrderStateContext.YANGLUO_SUPP_ID);
        return erpOrderProductionService.queryPageProductionList(params);
    }

    /**
     * 获取生产商列表
     */
    @RequestMapping("/getProducerList")
    public R getProducerList(@RequestParam("producerName") String producerName){
        return erpOrderProductionService.getProducerList(producerName);
    }

    /**
     * 门店生产列表（审核完成操作）
     */
    @RequestMapping("/storelist")
    public R storelist(@RequestParam Map<String, Object> params) {
        return erpOrderProductionService.storelist(params);
    }

    /**
     * 商户生产列表（验货确定操作）
     */
    @RequestMapping("/sellerlist")
    public R sellerlist(@RequestParam Map<String, Object> params) {
        return erpOrderProductionService.sellerlist(params);
    }

    /**
     * 财务生产成本 -列表
     */
    @RequestMapping("/productcostlist")
    public R productcostlist(@RequestBody Map<String, Object> params) {
        return erpOrderProductionService.productcostlist(params);
    }

    /**
     * 快递单信息
     *
     * @param orderNo
     * @return
     */
    @RequestMapping("/expressFormInfo/{orderNo}")
    public R expressFormInfo(@PathVariable("orderNo") String orderNo) {
        return erpOrderProductionService.queryExpressFormInfo(orderNo);
    }

    /**
     * 外协商验货确定
     *
     * @param productionId
     * @return
     */
    @RequestMapping("/supplierConfirmReceive")
    public R supplierConfirmReceive(@RequestParam("productionId") Integer productionId) {
        return erpOrderProductionService.supplierConfirmReceive(productionId);
    }

    /**
     * 验货确定
     *
     * @param productionId
     * @return
     */
    @RequestMapping("/confirmReceive")
    public R confirmReceive(@RequestParam("productionId") Integer productionId) {
        return erpOrderProductionService.confirmReceive(productionId);
    }

    /**
     * 审核完成
     *
     * @param productionId
     * @return
     */
    @RequestMapping("/auditFinish")
    public R auditFinish(@RequestParam("productionId") Integer productionId) {
        return erpOrderProductionService.auditFinish(productionId);
    }

    /**
     * 调价
     *
     * @return
     */
    @RequestMapping("/orderDiscount")
    public R orderDiscount(@RequestBody ProductionCostDto productionCostDto) {
        String username = UserUtils.getCurentUser().getUsername();
        return erpOrderProductionService.orderDiscount(productionCostDto, username);
    }

    /**
     * lu 成本录入
     * 添加成本价
     */
    @RequestMapping("/updatecost")
    public R updatecost(@RequestBody ErpOrderProductionEntity erpOrderProduction) {
        erpOrderProduction.setUpdateName("" + UserUtils.getCurentUser().getUserId());
        erpOrderProductionService.updatecost(erpOrderProduction);

        return R.ok();
    }

    /**
     * 生产成本批量录入
     * @param productionIds
     * @return
     */
    @RequestMapping("/batchEnteringCost")
    public R batchEnteringCost(@RequestBody Integer[] productionIds){
        return erpOrderProductionService.batchEnteringCost(productionIds);
    }

    /*lu
     * 生产成本价 /审核
     *
     */
    @RequestMapping("/toExamine")
    public R toExamine(@RequestParam("productionId") Integer productionId) {
        erpOrderProductionService.toExamine(productionId);
        return R.ok();
    }


    /**
     * 生产成本价 批量审核
     *
     * @param productionIds
     * @return
     */
    @RequestMapping("/toBatchExamine")
    public R toBatchExamine(@RequestParam("productionIds") String productionIds) {
        return erpOrderProductionService.toBatchExamine(productionIds);
    }

    /*
     * 生产成本
     * 订单作废
     */

    @RequestMapping("/toDead")
    public R toDead(@RequestBody ErpOrderProductionEntity erpOrderProduction) {
        erpOrderProductionService.toDead(erpOrderProduction);
        return R.ok();
    }

    /*
     * 生产成本
     * 订单撤回待审
     */
    @RequestMapping("/toWithdraw")
    public R toWithdraw(@RequestParam("productionId") Integer productionId) {
        erpOrderProductionService.toWithdraw(productionId);
        return R.ok();
    }

    /*
     * 生产成本
     *  财务付款
     */
    @RequestMapping("/toPayment")
    public R toPayment(@RequestBody FinancePaymentDto financePaymentDto) {
        financePaymentDto.setUserId(UserUtils.getCurentUser().getUserId());
        return erpOrderProductionService.toPayment(financePaymentDto);
    }

    /**
     * 外协金额计算
     */
    @RequestMapping("/productionCostCount")
    public R productionCostCount(@RequestBody Integer[] productionIds) {
        return erpOrderProductionService.productionCostCount(productionIds);
    }

    /**
     * 生产单复审
     */
    @RequestMapping("/review")
    public R review(@RequestParam("productionId") Integer productionId) {
        return erpOrderProductionService.review(productionId);
    }

    /**
     * 查询订单源文件
     */
    @RequestMapping("/orderSourceFile")
    public R orderSourceFile(@RequestParam("productionId") Integer productionId) {
        return erpOrderProductionService.orderSourceFile(productionId);
    }

    /**
     * excel 导出
     */
    @RequestMapping("/exportExcel")
    public void exportExcel(HttpServletRequest request, HttpServletResponse response) {
        String data = request.getParameter("postData");
        Map<String, Object> params = JsonUtils.string2Map(data);
        params.put("producer", ErpOrderStateContext.YANGLUO_SUPP_ID);
        // 查询列表数据
        List<ErpOrderProductionListVo> list = erpOrderProductionService.exportExcel(params);
        FileUtil.exportExcel(list, "阳逻生产表", "阳逻生产表", ErpOrderProductionListVo.class, "阳逻生产表.xls", response);
    }

}
